package cn.edu.gzgs.controller;

import cn.edu.gzgs.service.ProjectService;
import cn.edu.gzgs.service.impl.ProjectServicelmpl;
import cn.edu.gzgs.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/project")
@Tag(name = "项目管理接口")
@Slf4j
public class ProjectController {

    // 自动装配 ProjectService
    @Autowired
    private ProjectService projectService;

    @GetMapping("/tree")
    @Operation(summary = "获取项目-名单树")
    public ResponseEntity<ApiResponse<List<ProjectTreeVO>>> getProjectTree() {
        List<ProjectTreeVO> tree = projectService.getProjectTree();
        return ResponseEntity.ok(new ApiResponse<>(200, "获取成功", tree));
    }

    @GetMapping("/list/{id}")
    public ResponseEntity<ApiResponse<ListDetailResponse>> getListDetail(
            @PathVariable String id) {

        // 记录日志
        log.info("操作：获取名单明细 {}", id);

        // 校验ID格式
        if (!Pattern.matches("^[0-9]+\\.[0-9]+\\.[0-9]+$", id)) {
            log.warn("名单ID格式不正确: {}", id);
            return ResponseEntity.badRequest().body(
                    new ApiResponse<>(400, "名单ID格式不正确", null)
            );
        }

        try {
            ListDetailResponse response = projectService.getListDetail(id);
            return ResponseEntity.ok(
                    new ApiResponse<>(200,"获取成功", response)
            );
        } catch (ProjectServicelmpl.TableNotFoundException e) {
            log.error("名单表不存在: {}", id);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
                    new ApiResponse<>(404, "名单表不存在", null)
            );
        } catch (Exception e) {
            log.error("获取名单明细失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(
                    new ApiResponse<>(500, "服务器错误", null)
            );
        }
    }

    @GetMapping("/projects")
    @Operation(summary = "获取所有项目列表")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getAllProjects() {
        log.info("操作：获取所有项目列表");

        try {
            List<Map<String, Object>> projects = projectService.getAllProjects();
            return ResponseEntity.ok(
                    new ApiResponse<>(200, "获取成功", projects)
            );
        } catch (Exception e) {
            log.error("获取项目列表失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(
                    new ApiResponse<>(500, "服务器错误", null)
            );
        }
    }

    @GetMapping("/meta")
    @Operation(summary = "获取名单元数据列表")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getListMeta(
            @RequestParam(value = "project_id", required = false) String projectId,
            @AuthenticationPrincipal UserDetails userDetails) {

        log.info("操作：获取名单元数据, project_id: {}", projectId);

        try {
            // 从认证信息中获取用户ID
            String username = userDetails.getUsername();

            // 转换用户ID格式（例如 "U0002" -> "3002"）
            String leaderId = convertUserId(username);

            // 获取名单元数据
            List<Map<String, Object>> data = projectService.getListMetaByLeader(leaderId, projectId);
            return ResponseEntity.ok(
                    new ApiResponse<>(200, "获取成功", data)
            );
        } catch (Exception e) {
            log.error("获取名单元数据失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(new ApiResponse<>(500, "服务器错误", null));
        }
    }

    // 用户ID转换方法
    private String convertUserId(String username) {
        if (username.startsWith("U")) {
            // 示例转换：U0002 -> 3002
            return String.valueOf(3000 + Integer.parseInt(username.substring(1)));
        }
        return username; // 默认处理
    }

    @PostMapping("/declare")
    @Operation(summary = "申报名单表")
    public ResponseEntity<ApiResponse<DeclareResponse>> declareList(
            @RequestBody DeclareRequest request,
            @AuthenticationPrincipal UserDetails userDetails) {

        log.info("操作：申报名单表, projectId: {}", request.getProjectId());

        try {
            // 验证参数
            if (request.getProjectId() == null || request.getTableName() == null ||
                    request.getColumns() == null || request.getData() == null) {
                return ResponseEntity.badRequest()
                        .body(new ApiResponse<>(400, "参数错误", null));
            }

            // 获取 leaderId
            String leaderId = userDetails.getUsername();
            leaderId = convertUserId(leaderId);

            // 执行申报
            DeclareResponse response = projectService.declareList(
                    leaderId,
                    request.getProjectId(),
                    request.getTableName(),
                    request.getColumns(),
                    request.getData()
            );

            return ResponseEntity.ok(
                    new ApiResponse<>(200, "申报成功", response)
            );
        } catch (Exception e) {
            log.error("申报失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(new ApiResponse<>(500, "服务器错误", null));
        }
    }
}